<?php
namespace Ardon\EucpSms;
use Ardon\EucpSms\MagicCrypt;

class Eucp
{
    public static function http_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, true);
        $header[] = "appId: " . config('eucpsms.ym_sms_appid');
        if (true == config('eucpsms.en_gzip'))
        {
            $header[] = "gzip: on";
        }
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($curl, CURLOPT_HEADER, true);
        if (!empty($data))
        {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $res = curl_exec($curl);

        $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        curl_close($curl);

        $header = substr($res, 0, $headerSize);

        $outobj = [];

        $lines = explode("\r\n",$header);
        foreach($lines as $line)
        {
            $items = explode(": ",$line);
            if(isset($items[0]) AND !empty($items[0]) AND isset($items[1]) AND !empty($items[1]))
            {
                $outobj[$items[0]] = $items[1];
            }
        }

        $outobj['ciphertext'] = substr($res, $headerSize);

        return $outobj;
    }


    static function getMillisecond()
    {
        list($t1, $t2) = explode(' ', microtime());

        return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
    }

    public static function SendSMS($mobile, $content, $timerTime = "", $customSmsId = "", $extendedCode = "", $validPeriodtime= 120)
    {
        // 如果您的系统环境不是UTF-8，内容需要转码到UTF-8。如下：从gb2312转到了UTF-8
        // $content = mb_convert_encoding( $content,"UTF-8","gb2312");

        $item = [];
        $item['mobile']   = $mobile;
        $item['content']  = $content;

        /* 选填内容 */
        if("" != $timerTime)    $item['timerTime']    = $timerTime;
        if("" != $customSmsId)  $item['customSmsId']  = $customSmsId;
        if("" != $extendedCode) $item['extendedCode'] = $extendedCode;

        $item['requestTime'] = self::getMillisecond();
        $item['requestValidPeriod'] = $validPeriodtime;

        $json_data = json_encode($item, JSON_UNESCAPED_UNICODE);

        $senddata = MagicCrypt::encrypt($json_data);//加密结果

        $url = config('eucpsms.ym_sms_addr').config('eucpsms.ym_sms_send_uri');

        $resobj = self::http_request($url, $senddata);

        $resobj['plaintext'] = MagicCrypt::decrypt($resobj['ciphertext']);

        return $resobj;
    }

    public static function SendBatchSMS($mobiles, $content, $timerTime = "", $customSmsId = "", $extendedCode = "", $validPeriodtime= 120)
    {
        $item = [];

        $smses = array();
        foreach($mobiles as $mobile)    $smses[] = $mobile;

        $item['smses']   = $smses;

        // 如果您的系统环境不是UTF-8，内容需要转码到UTF-8。如下：从gb2312转到了UTF-8
        // $content = mb_convert_encoding( $content,"UTF-8","gb2312");

        $item->content  = $content;
        /* 选填内容 */
        if("" != $timerTime)    $item['timerTime']    = $timerTime;
        if("" != $customSmsId)  $item['customSmsId']  = $customSmsId;
        if("" != $extendedCode) $item['extendedCode'] = $extendedCode;

        $item['requestTime'] = getMillisecond();
        $item['requestValidPeriod'] = $validPeriodtime;

        $json_data = json_encode($item, JSON_UNESCAPED_UNICODE);

        $senddata = MagicCrypt::encrypt($json_data);//加密结果

        $url = $this->config['YM_SMS_ADDR'].$this->config['YM_SMS_SEND_URI'];

        $resobj = self::http_request($url, $senddata);

        $resobj->plaintext = MagicCrypt::decrypt($resobj->ciphertext);

        return $resobj;
    }

    public static function sendBatchOnlySMS($mobiles, $content, $timerTime = "", $customSmsId = "", $extendedCode = "", $validPeriodtime= 120)
    {
        // 如果您的系统环境不是UTF-8，内容需要转码到UTF-8。如下：从gb2312转到了UTF-8
        // $content = mb_convert_encoding( $content,"UTF-8","gb2312");

        $item = [];

        $item['mobiles']  = $mobiles;
        $item['content']  = $content;
        /* 选填内容 */
        if("" != $timerTime)    $item['timerTime']    = $timerTime;
        if("" != $extendedCode) $item['extendedCode'] = $extendedCode;

        $item['requestTime'] = getMillisecond();
        $item['requestValidPeriod'] = $validPeriodtime;

        $json_data = json_encode($item, JSON_UNESCAPED_UNICODE);

        $senddata = MagicCrypt::encrypt($json_data);//加密结果

        $url = config('eucpsms.ym_sms_addr') . config('eucpsms.ym_sms_send_batchonly_sms_uri');

        $resobj = self::http_request($url, $senddata);

        $resobj->plaintext = MagicCrypt::decrypt($resobj->ciphertext);

        return $resobj;
    }

    public static function sendPersonalitySMS($mobiles, $timerTime = "", $customSmsId = "", $extendedCode = "", $validPeriodtime= 120)
    {
        // 如果您的系统环境不是UTF-8，内容需要转码到UTF-8。如下：从gb2312转到了UTF-8
        // $content = mb_convert_encoding( $content,"UTF-8","gb2312");

        $item = [];

        $smses = array();
        foreach($mobiles as $mobile)    $smses[] = $mobile;

        $item['smses']   = $smses;

        /* 选填内容 */
        if("" != $timerTime)    $item['timerTime']    = $timerTime;
        if("" != $customSmsId)  $item['customSmsId']  = $customSmsId;
        if("" != $extendedCode) $item['extendedCode'] = $extendedCode;

        $item['requestTime'] = getMillisecond();
        $item['requestValidPeriod'] = $validPeriodtime;

        $json_data = json_encode($item, JSON_UNESCAPED_UNICODE);

        $senddata = MagicCrypt::encrypt($json_data);//加密结果

        $url = config('eucpsms.ym_sms_addr') . config('eucpsms.ym_sms_send_personality_sms_uri');
        $resobj = self::http_request($url, $senddata);
        $resobj->plaintext = MagicCrypt::decrypt($resobj->ciphertext);

        return $resobj;
    }

    public static function getReport($number = 0, $validPeriodtime= 120)
    {
        $item = [];
        /* 选填内容 */
        if(0 != $number)    $item['number']    = $number;

        $item->requestTime = getMillisecond();
        $item->requestValidPeriod = $validPeriodtime;

        $json_data = json_encode($item, JSON_UNESCAPED_UNICODE);

        $senddata = MagicCrypt::encrypt($json_data);//加密结果

        $url = config('eucpsms.ym_sms_addr') . config('eucpsms.ym_sms_getreport_uri');

        $resobj = self::http_request($url, $senddata);

        $resobj['plaintext'] = MagicCrypt::decrypt($resobj['ciphertext']);

        return $resobj;
    }

    public static function getMo($number = 0, $validPeriodtime= 120)
    {
        $item = [];
        /* 选填内容 */
        if(0 != $number)    $item['number']    = $number;

        $item['requestTime'] = self::getMillisecond();
        $item['requestValidPeriod'] = $validPeriodtime;

        $json_data = json_encode($item, JSON_UNESCAPED_UNICODE);

        $senddata = MagicCrypt::encrypt($json_data);//加密结果

        $url = config('eucpsms.ym_sms_addr') . config('eucpsms.ym_sms_getmo_uri');

        $resobj = self::http_request($url, $senddata);

        $resobj['plaintext'] = MagicCrypt::decrypt($resobj['ciphertext']);

        return $resobj;
    }

    public static function getBalance($validPeriodtime= 120)
    {
        $item = [];

        $item['requestTime'] = self::getMillisecond();
        $item['requestValidPeriod'] = $validPeriodtime;

        $json_data = json_encode($item, JSON_UNESCAPED_UNICODE);

        // echo "[send json is] :".END;
        // echo "".$json_data.END;

        $senddata = MagicCrypt::encrypt($json_data);//加密结果

        $url = config('eucpsms.ym_sms_addr') . config('eucpsms.ym_sms_getbalance_uri');
        $resobj = self::http_request($url, $senddata);
        $resobj['plaintext'] = MagicCrypt::decrypt($resobj['ciphertext']);

        return $resobj;
    }

    // 调试
    public function run(){
        echo "***************测试单条短信发送***************".END;
        $resobj = SendSMS("18001000000", "【某某公司】您的验证码是123");/* 短信内容请以商务约定的为准，如果已经在通道端绑定了签名，则无需在这里添加签名 */
        $resobj->ciphertext = "";
        echo "[result json is] :".END;
        echo "".$resobj->plaintext.END;
        echo "***************测试单条短信发送完成***************".END;
        //==========================================================================================
        echo "***************测试多条短信发送(支持SMSID)***************".END;
        $mobiles = array();
        $mobiles[] = new stdClass();
        $mobiles[0]->mobile         = "18001000000";
        $mobiles[0]->customSmsId    = "123";
        $mobiles[] = new stdClass();
        $mobiles[1]->mobile         = "18001000001";
        $mobiles[1]->customSmsId    = "321";

        $resobj = SendBatchSMS($mobiles, "【某某公司】您的验证码是123");/* 短信内容请以商务约定的为准，如果已经在通道端绑定了签名，则无需在这里添加签名 */
        $resobj->ciphertext = "";
        echo "[result json is] :".END;
        echo "".$resobj->plaintext.END;
        echo "***************测试多条短信发送(支持SMSID)完成***************".END;
        //==========================================================================================
        echo "***************测试多条短信发送(不支持SMSID)***************".END;
        $mobiles = array();
        $mobiles[] = "18001000000";
        $mobiles[] = "18001000001";

        $resobj = sendBatchOnlySMS($mobiles, "【某某公司】您的验证码是123");
        $resobj->ciphertext = "";
        echo "[result json is] :".END;
        echo "".$resobj->plaintext.END;
        echo "***************测试多条短信发送(不支持SMSID)完成***************".END;
        //==========================================================================================
        echo "***************测试个性短信接口***************".END;
        $mobiles = array();
        $mobiles[] = new stdClass();
        $mobiles[0]->mobile         = "18001000000";
        $mobiles[0]->customSmsId    = "1111111";
        $mobiles[0]->content        = "我是个性1号";
        $mobiles[] = new stdClass();
        $mobiles[1]->mobile         = "18001000001";
        $mobiles[1]->customSmsId    = "2222222";
        $mobiles[1]->content        = "我是个性2号";
        $mobiles[] = new stdClass();
        $mobiles[2]->mobile         = "18001000002";
        $mobiles[2]->customSmsId    = "3333333";
        $mobiles[2]->content        = "我是个性3号";

        $resobj = sendPersonalitySMS($mobiles);
        $resobj->ciphertext = "";
        echo "[result json is] :".END;
        echo "".$resobj->plaintext.END;
        echo "***************测试个性短信接口完成***************".END;
        //==========================================================================================
        echo "***************测试状态报告接口***************".END;
        $resobj = getReport();
        $resobj->ciphertext = "";
        echo "[result json is] :".END;
        echo "".$resobj->plaintext.END;
        echo "***************测试状态报告接口完成***************".END;
        //==========================================================================================
        echo "***************测试上行接口***************".END;
        $resobj = getMo();
        $resobj->ciphertext = "";
        echo "[result json is] :".END;
        echo "".$resobj->plaintext.END;
        echo "***************测试上行接口完成***************".END;
        //==========================================================================================
        echo "***************测试余额接口***************".END;
        $resobj = getBalance();
        $resobj->ciphertext = "";
        echo "[result json is] :".END;
        echo "".$resobj->plaintext.END;
        echo "***************测试余额接口完成***************".END;
    }

}